
import axios from 'axios'
import {data as dataAPI} from '@/api'
import Clipboard from 'clipboard'
import {format} from '@/utils/date'

let qs = require('qs');

export default{

	props: {
        data: Object,
        isPrivate: {
            type: Boolean,
            default: false
        },
        type: String,
        dataType: String,
        currentMenu: String,
    },

    data() {
        let showWgs84DownloadOption = this.$root.showWgs84DownloadOption != undefined ? 
            this.$root.showWgs84DownloadOption : false;
            
        let role = this.$root.geohey.user.role || '';    // 用户角色
        return {
            editName: false,
            dataName: this.data.name,
            uid: this.data.uid,
            oldName:'',
            prepareing: false,
            refreshing: false,
            showSubOption: false,
            showWgs84DownloadOption:  showWgs84DownloadOption == 'true',
            role: role,
            allowDownload: window.geohey_function_switch.download == 'true',
            timestamp: '',
            orgUid: this.$root.org.orgUid,
        }
    },

    filters: {
        timeFormat: (value) => {
            // var date = new Date(value);
            // return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
            
            return value ? format(value, 'Y-MM-DD hh:mm') : '';
        }
    },

    computed: {
        imageUrl () {
            let url = this.isPrivate ? this.dataType : `public_${this.dataType}` ;
            
            if(this.isPrivate&&this.data_nav_key=='private-data'){
                let dom = document.querySelector('.private-upload-res');
                if(!dom.classList.contains('active')){
                    url="public_data";
                }
            }
            return `/s/${url}/${this.data.uid}/thumb${(this.isPrivate && this.timestamp) ? `?t=${this.timestamp}` :''}`;
        },
        data_nav_key(){
            return this.$store.state.data_nav_key;
        },
        dataIcon () {
            let type = this.data.hasOwnProperty('geometryType') ? this.data. geometryType : 'imagery';

            if (this.isPrivate && this.data.hasOwnProperty('convertEnd')  && !this.data.convertEnd) {
                    return 'icon-unconverted';
            }

            let iconType = {
                pt: 'icon-pt',
                mpt: 'icon-pt',
                pl: 'icon-pl',
                mpl: 'icon-pl',
                imagery: 'icon-imagery',
            }
            return iconType.hasOwnProperty(type) ? iconType[type]: 'icon-unconverted';
            
        },
    },

    methods: {

        toggleMenu(type) {

            let currentMenu = `${this.uid}_${type}`;

            if (this.currentMenu === currentMenu) {
                this.$emit('set-current-menu', '');
                return;
            }

            this.$emit('set-current-menu', `${this.uid}_${type}`);
        },

        closeMenu() {

            this.$emit('set-current-menu', '');

        },

        imgLoaded(e) {
            e.target.style.opacity = 1;
        },

        dataPreview() {
            this.$emit('data-preview', this.data);
        },

        share() {

            if (!this.data.convertEnd) {
                this.$message.warning('数据尚未空间化，无法分享');
                return;
            }
            
            
            this.$emit('data-share', this.data, this.dataName);

        },

        addStar(){
            this.$emit('data-store', this.data);
        },

        copyUid() {
            let button = document.createElement('button');
            let uid = this.uid;

            let clipboard = new Clipboard(button, {
                text: () => {
                    return uid;
                }
            });

            clipboard.on('success', (e) => {
                e.clearSelection();
                this.$message.success('数据uid已复制到剪切板');
                clipboard.destroy();
            });

            clipboard.on('error', (e) => {
                this.$message.error('复制失败')
            });

            button.click();
        },

        openWithDataEditor() {

            if (!this.data.convertEnd) {
                this.$emit('open-spatializ-warning', this.uid);
                return;
            }
            
            window.open(`/apps/data-editor/${this.uid}`);
        },

        openWithDataViz() {

            if( !this.data.geometryType && this.dataType !== 'imagery'){
                this.$emit('data-preview', this.data);
                return;
            }
            
            if(this.dataType === 'imagery'){
                window.open(`/apps/dataviz/new/edit?datauid=${this.uid}&datatype=${this.type}_${this.dataType}`);
                return;
            }
            
            if(this.$store.state.data_nav_key == 'private-data'){
                let dom = document.querySelector('.private-upload-res');
                if(!dom.classList.contains('active')){
                    window.open(`/apps/dataviz/new/edit?datauid=${this.uid}&datatype=public`);
                    return;
                }
            }

            window.open(`/apps/dataviz/new/edit?datauid=${this.uid}&datatype=${this.isPrivate? 'private' : 'public'}`);
        },

        validation(e) {

            let val = this.dataName.replace(/[@#:;\$%\^&\*\\、\+\=<>\[\]\{\}\|?!,，。？'"’”【】\/\~\`]+/g, '');
            this.dataName = val;

        },

        startEdit(id) {

            if (!this.isPrivate || this.type === 'star') return;

            this.editName = true;

            this.oldName = this.dataName;

            this.$nextTick(function () {
                document.getElementById(id).focus();
            })

        },

        stopEdit() {

            if (this.oldName === this.dataName) {
                this.editName = false;
                return;
            }

            if (this.editName) {
                this.editName = false;
                this.rename();
            }

        },

        rename() {

            let params = {
                name: this.dataName
            }

            let header = {'Content-Type': 'application/x-www-form-urlencoded' };
            axios.post(`/s/data/${this.data.uid}/rename`, qs.stringify(params), {headers:header})

                .then((res) => {
                    if (res.data.code !=0) {
                        this.$message.error('数据重命名失败');
                        this.dataName = this.oldName;
                        return;
                    }
                    this.data.name = this.dataName;
                    this.$message.success('数据重命名成功');
                })
                .catch((err) => {
                    this.$message.error('数据重命名失败');
                    this.dataName = this.oldName;
                })
        },

        removeData () {
            this.$emit('remove', this.data, this.dataName);
        },

        moveOutStore () {
            this.$emit('move-out-store', this.data);
        },

        download (type, srs) {

            this.prepareing = true;

            let header = {'Content-Type': 'application/json'};
            axios.post(`/s/data/${this.data.uid}/download/${type}/${srs}`)
                .then((res) => {
                    let code = res.data.code;

                    if (this.type === 'star' && code === 601) {
                        this.$message.warning('群组数据暂不支持下载');
                        this.prepareing = false;
                        return;
                    }

                    if (code != 0) {
                        let msg = res.data.msg;

                        if (msg) {
                            this.$message.error(msg);
                        }

                        this.prepareing = false;

                        return;
                    }

                    this.getDownloadStatus(type, srs);

                })
                .catch((err) => {
                    this.$message.error('下载失败');
                    this.prepareing = false;
                })

        },

        getDownloadStatus (type, srs) {
            axios.post(`/s/data/${this.data.uid}/download/${type}/${srs}/status`)
                .then((res) => {
                    let code = res.data.code;
                    if (code != 0) {
                        let msg = res.data.msg;

                        if (msg) {
                            this.$message.error(msg);
                        }

                        this.prepareing = false;

                        return;
                    }

                    let data = res.data.data;
                    let status = data.status;

                    if (status === -1) {
                        this.$message.error(data.msg);
                        this.prepareing = false;
                        return;
                    }

                    if (status === 0 || status === 1) {

                        setTimeout(() => {
                            this.getDownloadStatus(type, srs);
                        },3000);

                    }

                    if (status === 2) {
                        this.downloadFile(data.url);
                    }

                })
                .catch((err) => {
                    this.$message.error('下载失败');
                    this.prepareing = false;
                })
        },

        downloadFile(url) {
            let downloadIframe = document.getElementById('downloadIframe');

            if (!downloadIframe) {
                downloadIframe = document.createElement("iframe");
                downloadIframe.id = "downloadIframe";
                downloadIframe.style.display = "none";
            }

            if (url.indexOf('http') === 0) {
                url = url.split(':').slice(1).join('');
            }

            downloadIframe.src = url;

            document.body.appendChild(downloadIframe);

            this.prepareing = false;
        },

        refreshThumb() {

            if (this.refreshing) {
                return;
            }

            this.refreshing = true;
            let uid = this.uid;

            dataAPI.refresh(
                uid,
                (res) =>{
                    if (res.data.code != 0) {
                        this.$message.error('刷新缩略图失败');
                        this.refreshing = false;

                        return;
                    }

                    this.refreshing = false;

                    this.$nextTick(() => {

                        this.$refs[`thumb-${uid}`].src=`/s/data/${uid}/thumb?timestamp=${Date.now()}`;
                    })
                },
                (err) => {
                    this.$message.error('刷新缩略图失败');
                    this.refreshing = false;
                    return;
                }

            )

        },

        showSrsDialog() {
            this.showSubOption = true;
        },

        hideSrsDialog() {
            this.showSubOption = false;
        }
    }
}